﻿using KZ.Express.ENT;
using KZ.Express.Presenter;
using KZ.Express.Resource;
using KZ.Utilities;
using System;
using System.Data;
using System.Windows.Forms;

namespace KZ.Express.Setup.PriceList
{
    public partial class OriginalPriceDetailView : FormBase, IOriginalPriceDetailView
    {
        #region Private Variables

        object _previousValue;
        DataTable _tblDOX, _tblWPX;
        new OriginalPriceDetailPresenter _presenter;

        #endregion Private Variables

        #region Private Methods

        private void OriginalPriceDetailView_Load(object sender, EventArgs e)
        {
            LoadCarrier();
            LoadZone();
            LoadData();
        }

        private void dtgDOXDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.PreviewKeyDown -= DOXControl_PreviewKeyDown;
            e.Control.PreviewKeyDown += DOXControl_PreviewKeyDown;
        }

        private void dtgDOXDetail_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    e.SuppressKeyPress = true;
                    if (dtgDOXDetail.CurrentCell.ColumnIndex == colTemp.Index)
                    {
                        if (dtgDOXDetail.CurrentRow.Index == dtgDOXDetail.RowCount - 1)
                            break;
                        dtgDOXDetail.CurrentCell = dtgDOXDetail[2, dtgDOXDetail.CurrentCell.RowIndex + 1];
                    }
                    else
                        SendKeys.Send("{TAB}");
                    break;
            }
        }

        private void dtgDOXDetail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (!dtgDOXDetail.CurrentCell.ReadOnly)
                dtgDOXDetail.BeginEdit(true);
        }

        private void dtgDOXDetail_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            _previousValue = dtgDOXDetail[e.ColumnIndex, e.RowIndex].Value;
        }

        private void dtgDOXDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            dtgDOXDetail[e.ColumnIndex, e.RowIndex].Value = _previousValue;
        }

        private void DOXControl_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (dtgDOXDetail.CurrentCell.ColumnIndex == colTemp.Index - 1 ||
                    dtgDOXDetail.CurrentCell.ColumnIndex == colTemp.Index)
                {
                    if (dtgDOXDetail.CurrentRow.Index == dtgDOXDetail.RowCount - 1)
                        return;
                    dtgDOXDetail.CurrentCell = dtgDOXDetail[2, dtgDOXDetail.CurrentCell.RowIndex];
                }
                else
                {
                    dtgDOXDetail.EndEdit();
                    SendKeys.Send("{TAB}");
                }
            }
        }

        private void dtgWPXDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.PreviewKeyDown -= WPXControl_PreviewKeyDown;
            e.Control.PreviewKeyDown += WPXControl_PreviewKeyDown;
        }

        private void dtgWPXDetail_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    e.SuppressKeyPress = true;
                    if (dtgWPXDetail.CurrentCell.ColumnIndex == colTemp.Index)
                    {
                        if (dtgWPXDetail.CurrentRow.Index == dtgWPXDetail.RowCount - 1)
                            break;
                        dtgWPXDetail.CurrentCell = dtgWPXDetail[2, dtgWPXDetail.CurrentCell.RowIndex + 1];
                    }
                    else
                        SendKeys.Send("{TAB}");
                    break;
            }
        }

        private void dtgWPXDetail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (!dtgWPXDetail.CurrentCell.ReadOnly)
                dtgWPXDetail.BeginEdit(true);
        }

        private void dtgWPXDetail_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            _previousValue = dtgWPXDetail[e.ColumnIndex, e.RowIndex].Value;
        }

        private void dtgWPXDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            dtgWPXDetail[e.ColumnIndex, e.RowIndex].Value = _previousValue;
        }

        private void WPXControl_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (dtgWPXDetail.CurrentCell.ColumnIndex == colTemp.Index - 1 ||
                    dtgWPXDetail.CurrentCell.ColumnIndex == colTemp.Index)
                {
                    if (dtgWPXDetail.CurrentRow.Index == dtgWPXDetail.RowCount - 1)
                        return;
                    dtgWPXDetail.CurrentCell = dtgWPXDetail[2, dtgWPXDetail.CurrentCell.RowIndex];
                }
                else
                {
                    dtgWPXDetail.EndEdit();
                    SendKeys.Send("{TAB}");
                }
            }
        }

        private void cmbCarrierID_SelectedValueChanged(object sender, EventArgs e)
        {
            LoadSupplier();
        }

        private void cmbZoneID_SelectedValueChanged(object sender, EventArgs e)
        {
            LoadZoneDetail();
        }

        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            Import();
        }

        protected override void LoadData()
        {
            try
            {
                switch (base.Action)
                {
                    case ActionName.Insert:
                        break;

                    case ActionName.Update:
                        _presenter.LoadEntity();
                        _presenter.LoadDataTable();
                        break;
                }
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private void LoadCarrier()
        {
            try
            {
                cmbCarrierID.SelectedValueChanged -= cmbCarrierID_SelectedValueChanged;
                Global.LoadComboBox(cmbCarrierID, _presenter.LoadForCMB<CarrierENT>(null));
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
            finally
            {
                cmbCarrierID.SelectedValueChanged += cmbCarrierID_SelectedValueChanged;
            }
        }

        private void LoadSupplier()
        {
            try
            {
                SearchCriteria search = new SearchCriteria();
                search.Add("CarrierID", Utility.IntParse(cmbCarrierID.SelectedValue));
                Global.LoadComboBox(cmbSupplierID, _presenter.LoadForCMB<SupplierENT>(search));
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private void LoadZone()
        {
            try
            {
                cmbZoneID.SelectedValueChanged -= cmbZoneID_SelectedValueChanged;
                Global.LoadComboBox(cmbZoneID, _presenter.LoadForCMB<ZoneENT>(null));
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
            finally
            {
                cmbZoneID.SelectedValueChanged += cmbZoneID_SelectedValueChanged;
            }
        }

        private void LoadZoneDetail()
        {
            try
            {
                _presenter.LoadZoneDetail(Utility.IntParse(cmbZoneID.SelectedValue));
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        #endregion Private Methods

        #region Constructors

        public OriginalPriceDetailView()
        {
            InitializeComponent();
            base.ObjectID = (int)Objects.OriginalPriceList;

            cmbZoneID.DisplayColumns.Add("ZoneCode", "Mã");
            cmbZoneID.DisplayColumns.Add("ZoneName", "Tên");
            cmbZoneID.DropDownWidth = 250;
            cmbSupplierID.DisplayColumns.Add("PartnerCode", "Mã account");
            cmbSupplierID.DisplayColumns.Add("PartnerName", "Tên acount");
            cmbSupplierID.DropDownWidth = 250;

            _presenter = new OriginalPriceDetailPresenter(this);

            Global.SetDoubleBuffered(dtgDOXDetail);
            Global.SetDoubleBuffered(dtgWPXDetail);
        }

        #endregion Constructors

        #region Public Properties

        public DataTable ZoneTypes
        {
            set
            {
                for (int i = colTemp.Index - 1; i > colDOXWeight.Index; i--)
                {
                    dtgDOXDetail.Columns.RemoveAt(i);
                    dtgWPXDetail.Columns.RemoveAt(i);
                }
                _tblDOX = new DataTable();
                _tblDOX.Columns.Add("Number", typeof(int));
                _tblDOX.Columns.Add("Weight", typeof(string));

                _tblWPX = new DataTable();
                _tblWPX.Columns.Add("Number", typeof(int));
                _tblWPX.Columns.Add("Weight", typeof(string));

                int index = 1;
                int rowCount = value.Rows.Count;
                for (int i = rowCount - 1; i >= 0; i--)
                {
                    DataGridViewColumn colDOX = new DataGridViewColumn(dtgDOXDetail.Columns[colDOXWeight.Index].CellTemplate);
                    colDOX.Name = "colDOX" + value.Rows[i]["Zone"];
                    colDOX.HeaderText = value.Rows[i]["Zone"].ToString();
                    colDOX.DataPropertyName = value.Rows[i]["Zone"].ToString();
                    colDOX.Width = 60;
                    colDOX.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    colDOX.DefaultCellStyle.Format = "N2";

                    _tblDOX.Columns.Add(colDOX.DataPropertyName, typeof(decimal));
                    dtgDOXDetail.Columns.Insert(colDOXWeight.Index + index, colDOX);

                    DataGridViewColumn colWPX = new DataGridViewColumn(dtgWPXDetail.Columns[colWPXWeight.Index].CellTemplate);
                    colWPX.Name = "colWPX" + value.Rows[i]["Zone"];
                    colWPX.HeaderText = value.Rows[i]["Zone"].ToString();
                    colWPX.DataPropertyName = value.Rows[i]["Zone"].ToString();
                    colWPX.Width = 60;
                    colWPX.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    colWPX.DefaultCellStyle.Format = "N2";

                    _tblWPX.Columns.Add(colWPX.DataPropertyName, typeof(decimal));
                    dtgWPXDetail.Columns.Insert(colWPXWeight.Index + index, colWPX);
                }
            }
        }

        public DataTable TblDOX
        {
            get { return _tblDOX; }
            set
            {
                _tblDOX = value;
                bdsDOX.DataSource = value;
                Global.GenerateNumber(ref value);
            }
        }

        public DataTable TblWPX
        {
            get { return _tblWPX; }
            set
            {
                _tblWPX = value;
                bdsWPX.DataSource = value;
                Global.GenerateNumber(ref value);
            }
        }

        public override EntityBase Entity
        {
            get
            {
                OriginalPriceListENT priceList = new OriginalPriceListENT();
                priceList.PriceListID = base.EntityID;
                priceList.PriceListCode = txtPriceListCode.Text;
                priceList.PriceListName = txtPriceListName.Text;
                priceList.CarrierID = Utility.IntNParse(cmbCarrierID.SelectedValue);
                priceList.ZoneID = Utility.IntNParse(cmbZoneID.SelectedValue);
                priceList.SupplierID = Utility.IntNParse(cmbSupplierID.SelectedValue);
                priceList.EffectedDate = dtpEffectedDate.Value;
                priceList.ExpiredDate = dtpExpiredDate.Value;
                priceList.IsOriginal = true;

                return priceList;
            }
            set
            {
                OriginalPriceListENT priceList = value as OriginalPriceListENT;

                txtPriceListCode.Text = priceList.PriceListCode;
                txtPriceListName.Text = priceList.PriceListName;
                cmbCarrierID.SelectedValue = Utility.IntParse(priceList.CarrierID);
                cmbZoneID.SelectedValue = Utility.IntParse(priceList.ZoneID);
                cmbSupplierID.SelectedValue = Utility.IntParse(priceList.SupplierID);
                dtpEffectedDate.Value = Utility.DateTimeParse(priceList.EffectedDate);
                dtpExpiredDate.Value = Utility.DateTimeParse(priceList.ExpiredDate);
            }
        }

        #endregion Public Properties

        #region Public Methods

        public override void Save()
        {
            try
            {
                dtgDOXDetail.EndEdit();
                _presenter.Save();
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        public void Import()
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;

                dtgDOXDetail.CellEnter -= dtgDOXDetail_CellEnter;
                dtgWPXDetail.CellEnter -= dtgWPXDetail_CellEnter;
                try
                {
                    bdsDOX.DataSource = null;
                    bdsWPX.DataSource = null;
                    _presenter.ImportExcel(ofd.FileName);
                }
                finally
                {
                    dtgDOXDetail.CellEnter += dtgDOXDetail_CellEnter;
                    dtgWPXDetail.CellEnter += dtgWPXDetail_CellEnter;
                    Cursor = Cursors.Default;
                }
            }
        }

        #endregion Public Methods
    }
}